import * as Cesium from "cesium";
import Comtainer from "../components/Comtainer/index"; // 函数形容器组件
import Slot from "../components/Comtainer/slot.vue";

class ViewerEvents {
  constructor(viewer) {
    this.handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  }
}

export default class addLeftClickBillboardEvent extends ViewerEvents {
  constructor(viewer) {
    super(viewer);
    this.viewer = viewer;
    this.instance = null; // 组件实例的控制实例
    this.billbroadPosition = null; // 当前点击的广告牌的世界坐标
    this.init(); // 注册时间
  }
  init() {
    this.leftClick(); // 绑定鼠标点击广告牌事件
  }
  // 绑定鼠标点击广告牌事件
  leftClick() {
    const _this = this;
    const viewer = this.viewer;
    const scene = viewer.scene;
    const handler = this.handler;
    handler.setInputAction((event) => {
      const cartesian2 = event.position; // 鼠标点击的 平面位置
      const pick = scene.pick(cartesian2); // pick 是点击的物体
      if (Cesium.defined(pick)) {
        console.log("PICK 点击的物体信息", pick);
        _this.billbroadPosition = pick.id.position._value; // {广告牌的世界坐标}
        _this.instance = new Comtainer({
          el: "cesiumContainer",
          positionLeft: cartesian2.x + "px",
          positionTop: cartesian2.y + "px",
          contentId: "cesiumPop", // 子组件的DOM id  不要重复依赖这个找dom
          slot: Slot, // 需要渲染的vue 组件
        });
        // 地图移动时广告牌移动
        scene.postRender.addEventListener(
          _this.domPositionChangeBySceneChange,
          _this
        );
        console.log("注册了事件");
      } else {
        if (this.instance) {
          console.log("取消事件");
          // 点击其他位置 取消事件
          scene.postRender.removeEventListener(
            _this.domPositionChangeBySceneChange,
            _this
          );
          // 注销实例
          this.instance.close();
          this.instance = null;
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  }
  // 实时获取 广告牌的世界坐标对应最新的 屏幕坐标并设置到dom上
  domPositionChangeBySceneChange() {
    const scene = this.viewer.scene;
    const dom = document.getElementById(this.instance?.contentId);
    console.log("实时监听视图变化");
    if (this.billbroadPosition && dom) {
      const winpos = scene.cartesianToCanvasCoordinates(this.billbroadPosition);
      if (winpos) {
        const left = winpos.x.toFixed(0) + "px";
        const top = winpos.y.toFixed(0) + "px";
        dom.style.left = left;
        dom.style.top = top;
      }
    }
  }
}
